from rest_framework import serializers, exceptions
from rest_framework_simplejwt.serializers import PasswordField
from .models import User, Tenant


class RegistrationSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = PasswordField()
    first_name = serializers.CharField(required=False, default='')
    last_name = serializers.CharField(required=False, default='')

    def validate_email(self, value):
        # 验证： 该邮箱对应的 <租户,邮箱> 二元组是否 存在
        # 即，验证由<租户,邮箱> 二元组 生成的 schema 是否存在 
        # (因为假设了所有用户都是散户，即，一个用户独享一个租户)
        user_schema_name = User.get_default_schema(value)

        try:
            Tenant.objects.get(schema_name=user_schema_name)
            raise exceptions.ValidationError(f'{value} 已经存在')
        except Tenant.DoesNotExist:
            return value


class UserSerializer(serializers.ModelSerializer):

    tenant = serializers.StringRelatedField()
    # ser = UserSerializer(user_instance)
    # ser.data['tenant'] 得到的是用户租户的字符串格式
    #                    等价于 str(user_instance.tenant)

    id = serializers.ReadOnlyField()
    roles = serializers.StringRelatedField(many=True)

    class Meta:
        model = User
        fields = (
            'id',
            'email',
            'first_name',
            'last_name',
            'tenant',
            'roles',
            'created'
        )
